#! /usr/bin/python
#  -*- coding: utf-8 -*-

def nonstring_iterable(obj):
      try: iter(obj)
      except TypeError: return False
      else: return not isinstance(obj, basestring)

def flatten(sequence, to_expand=nonstring_iterable):
      iterators = [ iter(sequence) ]
      while iterators:
            # 循环当前的最深嵌套（最后）的迭代器
            for item in iterators[-1]:
                  if to_expand(item):
                        # 找到了子序列，循环子序列的迭代器
                        iterators.append(iter(item))
                        break
                  else:
                        yield item
            else:
                  # 最深嵌套的迭代器耗尽，回过头来循环它的父迭代器
                  iterators.pop( )


for x in flatten([1, 2, [3, [  ], 4, [5, 6], 7, [8,], ], 9]):
    print x,
